home *** CD-ROM | disk | FTP | other *** search
- /* CPROG11.CPP - Fill a 2D array, then print its contents */
-
- #include <stdio.h>
-
- void main(void)
- {
- int i, j, // Loop counters
- x, // Holds the value being put in the current array element
- grid[3][2]; // The array, called grid, is 3 rows of 2
- // Note how the declaration is split over several
- // lines - a carriage return is not the
- // end-of-declaration marker. The semi-colon is.
-
- // *********** Fill the array ************* //
- for(i=0, x=1; i<3; i++) // x=1; For each row...
- for(j=0; j<2; j++) // For each element in row...
- grid[i][j]=x++; // Insert x and increment it
-
- /* This uses a nested loop. The outer one, controlled by counter i,
- causes each row to be processed in turn. The inner loop runs along
- each row, putting the current value of x into the current element.
- There is no need to put the second two lines in braces. The outer
- loop executes the single statment after it (the j loop). That in turn
- executes the single statement after it.
- The first element in the for(i=0, x=1;... line is quite legal - you
- can have multiple statements, separated by commas, before the first
- semicolon. The same applies to the third element. */
-
-
-
- // ********** Print the array ************* //
-
- putchar('\n'); // Make sure we're on a new line
-
- for(i=0; i<3; i++)
- {
- for(j=0; j<2; j++)
- printf("%d ", grid[i][j]);
- putchar('\n');
- }
- /* This needs braces because there is more than one instruction to
- be executed for each iteration of the outer loop. When the j loop
- has processed a line, we print a newline character to start a new
- screen line. */
- }
-